package com.example.save;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class fragment2 extends Fragment {

    private static final String FILE_NAME = "Sfile";
    private Button writeExternalButton;
    private Button readExternalButton;

    public fragment2(){
        super(R.layout.fragment2);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState){
        writeExternalButton=getView().findViewById(R.id.writeExternalButton);
        writeExternalButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                File externalPath=getActivity().getExternalFilesDir(null);
                File file=new File(externalPath,FILE_NAME);
                try{
                    FileOutputStream os=new FileOutputStream(file);
                    BufferedWriter writer=new BufferedWriter(new OutputStreamWriter(os));
                    writer.write("I am come from China");
                    writer.close();
                    Toast.makeText(getActivity(),"写入成功",Toast.LENGTH_SHORT).show();
                }  catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        readExternalButton =getView().findViewById( R.id.readExternalButton);
        readExternalButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                File ExternalPath=getActivity().getExternalFilesDir(null);
                File file=new File(ExternalPath,FILE_NAME);

                try{
                    FileInputStream is =new FileInputStream(file);
                    BufferedReader reader=new BufferedReader(new InputStreamReader(is));
                    String line=reader.readLine();
                    Toast.makeText(getActivity(),line,Toast.LENGTH_SHORT).show();
                }
                catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });
    }
}
